package com.xq.filter;

import com.xq.result.Result;
import com.xq.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


@Component
public class GloBalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        //放松登录请求
        if(path.contains("/login")){
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst("Authorization");
        String EncodeToken = authorization.substring(7);
        if(!StringUtils.isEmpty(EncodeToken) && !EncodeToken.equals("null")){
            try{
                //解析Token
                Claims claims = JwtUtils.validateToken(EncodeToken);
                //判断权限
                System.out.println(claims.getSubject());
                if(claims.getSubject().equals("admin")){
                    return chain.filter(exchange);
                }
            }catch (Exception e){
              return ExceptionHandler(response,"登陆失效或权限不足");
            }
        }
        return ExceptionHandler(response,"未登录");
    }

    @Override
    public int getOrder() {
        return 0;
    }


    public Mono<Void> ExceptionHandler(ServerHttpResponse response, String message){
        Result<String> error = Result.error(message);
        byte[] bytes = error.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return response.writeWith(Mono.just(buffer));
    }
}
